<!--
 * @Author: chengjiang
 * @Date: 2024-11-12 10:01:43
 * @Description: 
-->
<template>
  <a-space direction="horizontal">
    <div class="clearfix">
      <a-upload v-model:file-list="fileList" :beforeUpload="handleBeforeUpload" action="" accept=".jpg,.jpeg,.png"
        list-type="picture-card" @preview="handlePreview">
        <div v-if="fileList && fileList.length < 5">
          <plus-outlined />
          <div style="margin-top: 8px">添加图片</div>
        </div>
      </a-upload>
      <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
    <p>配置为：</p>
    <a-select v-model:value="value" size="large" style="width: 200px" allowClear="true" :options="options"></a-select>
  </a-space>
  <p class="mt-5 mb-5 text-[#858688]">注意：仅支持【.jpg | .jpeg | .png】格式的图片，且图片大小建议为【2MB】以内。</p>
  <a-divider />
  <a-flex class="mb-10" justify="flex-end" align="center">
    <a-button class="editable-add-btn mb-2 mr-5" @click="clearFileList">取消</a-button>
    <a-button type="primary" class="editable-add-btn mb-2 mr-5" @click="upload">上传</a-button>
  </a-flex>
</template>
<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue';
import { ref, watch } from 'vue';
import type { UploadFile } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { GetPhoto, Photo, SavePhoto, UpdatePhoto } from '../../../api/home';

const prp = defineProps<{
  pageType: number // 0: 看价盘，1: customer临售盘
}>()
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const value = ref<number>();
const dataSource = ref<Photo[]>([]);
const fileList = ref<UploadFile[]>([
  // {
  //   uid: '-xxx',
  //   percent: 50,
  //   name: 'image.png',
  //   status: 'uploading',
  //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  // },
]);
// 获取数据库图片资源。
const initFunc = () => {
  GetPhoto({
    type: value.value !== undefined ? value.value as number : undefined,
    priceType: prp.pageType as number,
  }).then((res) => {
    fileList.value = [];
    for (const val of res.data) {
      fileList.value.push(
        {
          uid: `${val.type}`,
          name: 'image.png',
          status: 'done',
          url: val.content,
        },)
      dataSource.value.push({
        id: val.id,
        priceType: val.priceType,
        type: val.type,
        content: val.content,
      })
    }

  }).catch(
    () => {
      message.error('获取图片失败!')
    }
  )
}
initFunc();
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handlePreview = async (file: UploadFile) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj as File)) as string;
    console.log(file.preview);
  }
  previewImage.value = file.url || file.preview as string;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url?.substring(file.url.lastIndexOf('/') + 1) as string;
};
const handleBeforeUpload = async (file: File) => {
  // 这里可以添加任何你需要的逻辑
  console.log('Selected File:', file);
  // const maxSize = 2 * 1024 * 1024; // 2MB
  // if (file.size > maxSize) {
  //   message.error('图片大小建议不超过 2MB');
  // }
  // 返回 false 阻止文件上传
  message.success('图片选择成功');
  previewImage.value = (await getBase64(file)) as string;
  return false;
}

const upload = () => {
  if (value.value === undefined) {
    message.error('请选择图片类型');
    return
  }
  if (value.value === 3) {
    message.error('暂时不支持该类型上传');
    return
  }
  const maxSize = 2 * 1024 * 1024; // 2MB
  console.log('上传的大小：', previewImage.value.length, maxSize);
  if (previewImage.value.toString().length > maxSize) {
    message.error('图片大小不能超过 2MB');
    return
  }
  const tmp = dataSource.value.filter(item => item.type === value.value);
  if (tmp && tmp.length > 0) {
    UpdatePhoto(tmp[0].id!, {
      type: value.value as number,
      priceType: prp.pageType as number,
      content: previewImage.value
    }).then((res) => {
      message.info('更新图片成功')
      console.log(res)
    })
  } else {
    SavePhoto({
      type: value.value as number,
      priceType: prp.pageType as number,
      content: previewImage.value
    }).then((res) => {
      message.info('添加图片成功')
      console.log(res)
    })
  }
}

const options = [
  {
    value: 0,
    label: '系统logo',
  },
  {
    value: 1,
    label: '二维码',
  },
  {
    value: 2,
    label: '微信客服码',
  },
]
if (prp.pageType === 1) {
  options.push({
    value: 3,
    label: '临售盘首页图片',
  })
}
// 清理掉上传的图片
const clearFileList = () => {
  fileList.value = [];
}
// 监听：value，如果没有值，则fileList展示全部，为0则展示指定的图片。
watch(() => value.value, (newValue) => {
  initFunc();
  if (newValue === undefined) {
    return;
  }
  switch (newValue) {
    case 0:
      fileList.value = fileList.value.filter(item => item.uid === `0`);
      break
    case 1:
      fileList.value = fileList.value.filter(item => item.uid === `1`);
      break
    case 2:
      fileList.value = fileList.value.filter(item => item.uid === `2`);
      break
    case 3:
      fileList.value = fileList.value.filter(item => item.uid === `3`);
      break
    default:
      message.error('暂不支持其它类型图片');
      break
  }
})
</script>
<style scoped>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>